package com.powerhua.privilege.web.action.convert;

import com.powerhua.core.xml.XmlUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;

public class PageTemplate {

	static Logger logger = Logger.getLogger(PageTemplate.class);

	public static final String WEB_TEMPLATE_FILE = "web-template.xml";

	/**
	 * 
	 * @param templateName
	 * @return
	 */
	public static String getPageTemplate(String templateName) {
		Element templateElement = getElement(templateName);

		String templatePath = templateElement.elementText("path");
		String templateFile = templateElement.elementText("file");
		String templateStart = templateElement.elementText("start");
		String templateEnd = templateElement.elementText("end");

		String returnString = getPageTemplateContent(templatePath
				+ templateFile, templateStart, templateEnd);
		return returnString;
	}

	/**
	 * 
	 * @param file
	 * @param startStr
	 * @param endStr
	 * @return
	 */
	private static String getPageTemplateContent(String fileStr,
			String startStr, String endStr) {
		if (startStr == null || endStr == null) {
			logger.error("Load web page template error."
					+ " \nTemplate start node or end node is null."
					+ " \nFile is [" + fileStr + "].");
		}

		StringBuffer returnStrBuffer = new StringBuffer("");
		
		File file = new File(fileStr);
		try {
			FileInputStream fis = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis,
					"UTF-8"));
			
			String currentLineStr = "";
			while ((currentLineStr = br.readLine()) != null) {
				returnStrBuffer.append(currentLineStr);
			}
			fis.close();
			
		} catch (FileNotFoundException e) {
			String errorStr = "Load web page template error."
				+ "\nTemplate file not exist, file is [" + fileStr + "].";
			logger.error(errorStr);
		} catch (UnsupportedEncodingException e) {

		} catch (IOException e) {

		}
		
		return returnStrBuffer.toString();
	}

	/**
	 * 
	 * @param strId
	 * @return
	 */
	private static Element getElement(String strId) {
        Document doc = XmlUtil.getDocument(WEB_TEMPLATE_FILE);
        Element root = doc.getRootElement();
        Element element = root.element(strId);

        return element;
	}

}
